package com.qf.redpack.business.web.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.redpack.business.web.dao.RedpackDao;
import com.qf.redpack.business.web.service.RedpackService;
import com.qf.redpack.entity.Redpack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 红包表(Redpack)表服务实现类
 *
 * @author makejava
 * @since 2024-02-02 10:35:21
 */
@Service("redpackService")
public class RedpackServiceImpl extends ServiceImpl<RedpackDao, Redpack> implements RedpackService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送红包的业务
     * @param redpack
     * @return 红包的ID
     */
    @Override
    @Transactional
    public long sendRedPack(Redpack redpack) {
        //保存到数据库中
        this.save(redpack);
        System.out.println("生成的红包ID：" + redpack.getId());

        //将红包信息同步到Redis中
        stringRedisTemplate.opsForHash()
                .putAll("redpack:" + redpack.getId(),
                        MapUtil.builder()
                                .put("money", BigDecimal.valueOf(redpack.getTotalMoney()).multiply(BigDecimal.valueOf(100)).intValue() + "")
                                .put("count", redpack.getTotalCount().toString())
                                .put("type", redpack.getType().toString()).build());

        return redpack.getId();
    }
}

